<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="移交时间" prop="useTime" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_record_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:admFileTransfer:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:admFileTransfer:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:admFileTransfer:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:admFileTransfer:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admFileTransferList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="移交人" align="center" prop="transferId" >
          <template #default="scope">
            <span>{{ scope.row.transferName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="移交日期" align="center" prop="transferTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.transferTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属部门" align="center" prop="deptId" >
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="移交部门" align="center" prop="transferDeptId" >
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.transferDeptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="资料类型" align="center" prop="dataType" >
          <template #default="scope">
            <dict-tag :options="data_type_options" :value="scope.row.dataType" />
          </template>
        </el-table-column>
        <el-table-column label="资料名称" align="center" prop="dataName" >
          <template #default="scope">
            <el-tooltip :content="scope.row.dataName" placement="top" :disabled="!scope.row.dataName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.dataName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="资料归属公司" align="center" prop="dataOwnershipCompany" width="120">
          <template #default="scope">
            <el-tooltip :content="scope.row.dataOwnershipCompany" placement="top" :disabled="!scope.row.dataOwnershipCompany">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.dataOwnershipCompany }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="甲方" align="center" prop="partA" >
          <template #default="scope">
            <el-tooltip :content="scope.row.partA" placement="top" :disabled="!scope.row.partA">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.partA }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="乙方" align="center" prop="partB" >
          <template #default="scope">
            <el-tooltip :content="scope.row.partB" placement="top" :disabled="!scope.row.partB">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.partB }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="份数" align="center" prop="copies" />
        <el-table-column label="接收人" align="center" prop="recipientId" >
          <template #default="scope">
            <el-tooltip :content="scope.row.recipientName" placement="top" :disabled="!scope.row.recipientName">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.recipientName }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status" >
          <template #default="scope">
            <dict-tag :options="approval_record_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建日期" align="center" prop="createTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template #default="scope">
            <el-tooltip :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <div style="width: 100%; display: flex; justify-content: center; align-items: center;">
                <span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: center;">
                  {{ scope.row.remark }}
                </span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:admFileTransfer:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:admFileTransfer:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改档案移交对话框 -->
    <el-dialog 
      :title="dialog.title" 
      v-model="dialog.visible" 
      width="900px" 
      append-to-body
      class="seal-dialog"
    >
      <template #default>
        <el-form ref="admFileTransferFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="移交人" prop="transferName">
                <el-input v-model="form.transferName" placeholder="请输入移交人名称" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="安排移交时间" prop="transferTime">
                <el-date-picker clearable
                  v-model="form.transferTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择移交日期"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所属部门" prop="deptId">
                <el-tree-select
                    v-model="form.deptId"
                    :data="deptTree"
                    placeholder="请选择所属部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="移交部门" prop="transferDeptId">
                <el-tree-select
                    v-model="form.transferDeptId"
                    :data="deptTree"
                    placeholder="请选择移交部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="资料名称" prop="dataName">
                <el-input v-model="form.dataName" placeholder="请输入资料名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="资料归属公司" prop="dataOwnershipCompany">
                <el-input v-model="form.dataOwnershipCompany" placeholder="请输入资料归属公司" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="资料类型" prop="dataType">
                <el-select
                  v-model="form.dataType"
                  placeholder="请选择资料类型"
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="option in data_type_options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="甲方" prop="partA">
                <el-input v-model="form.partA" placeholder="请输入甲方" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="乙方" prop="partB">
                <el-input v-model="form.partB" placeholder="请输入乙方" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="份数" prop="copies">
                <el-input v-model="form.copies" placeholder="请输入份数" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="接收人员" prop="recipientId">
                <el-input
                  v-model="form.recipientName"
                  :placeholder="form.recipientName ? '' : '请选择接收人员'"
                  readonly
                  @click="openUserSelector()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

      <!-- 驾驶人和随行人选择对话框 -->
    <UserSelector
      v-model:visible="userSelectVisible"
      :title="userSelectTitle"
      :selected-user-ids="currentSelectedUserIds"
      :selected-user-names="currentSelectedUserNames"
      :multiple="isJoint"
      @confirmWithIds="handleUserSelectWithIds"
      @cancel="handleUserSelectCancel"
    />

  </div>
</template>

<script setup name="AdmFileTransfer" lang="ts">
import { listAdmFileTransfer, getAdmFileTransfer, delAdmFileTransfer, addAdmFileTransfer, updateAdmFileTransfer } from '@/api/general/administration/file/transfer';
import { AdmFileTransferVO, AdmFileTransferQuery, AdmFileTransferForm } from '@/api/general/administration/file/transfer/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const admFileTransferList = ref<AdmFileTransferVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 用户信息
const userStore = useUserStore();

// 引入数据字典
const { data_type_options, approval_record_status } = toRefs<any>(proxy?.useDict('data_type_options', 'approval_record_status'));

const queryFormRef = ref<ElFormInstance>();
const admFileTransferFormRef = ref<ElFormInstance>();

// 驾驶人和随行人选择相关
const userSelectVisible = ref(false);
const userSelectTitle = ref('');
const isJoint = ref(false); // 区分使用人/共同使用人
const currentSelectedUserIds = ref('');
const currentSelectedUserNames = ref('');
const currentActualStage = ref<any>(null);
const currentSelectStageIndex = ref(-1);

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: AdmFileTransferForm = {
  id: undefined,
  transferId: userStore.userId,
  transferName: userStore.name,
  transferTime: formatLocalDate(),
  deptId: undefined,
  deptName: undefined,
  transferDeptId: undefined,
  transferDeptName: undefined,
  dataType: undefined,
  dataName: undefined,
  dataOwnershipCompany: undefined,
  partA: undefined,
  partB: undefined,
  copies: undefined,
  recipientId: undefined,
  recipientName: undefined,
  remark: undefined,
  status: undefined,
}
const data = reactive<PageData<AdmFileTransferForm, AdmFileTransferQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    transferName: [
      { required: true, message: '移交人不能为空', trigger: 'blur' }
    ],
    transferTime: [
      { required: true, message: '请选择安排移交时间', trigger: 'change' }
    ],
    deptId: [
      { required: true, message: '请选择所属部门', trigger: 'change' }
    ],
    transferDeptId: [
      { required: true, message: '请选择移交部门', trigger: 'change' }
    ],
    dataName: [
      { required: true, message: '请输入资料名称', trigger: 'blur' }
    ],
    dataOwnershipCompany: [
      { required: true, message: '请输入资料归属公司', trigger: 'blur' }
    ],
    dataType: [
      { required: true, message: '请选择资料类型', trigger: 'change' }
    ],
    partA: [
      { required: true, message: '请输入甲方', trigger: 'blur' }
    ],
    partB: [
      { required: true, message: '请输入乙方', trigger: 'blur' }
    ],
    copies: [
      { required: true, message: '请输入份数', trigger: 'blur' },
      { pattern: /^[1-9]\d*$/, message: '份数必须为正整数', trigger: 'blur' }
    ],
    recipientId: [
      { required: true, message: '请选择接收人员', trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询档案移交列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmFileTransfer(params);
    admFileTransferList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  admFileTransferFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmFileTransferVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加档案移交";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: AdmFileTransferVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getAdmFileTransfer(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改档案移交";
}

/** 提交按钮 */
const submitForm = () => {
  admFileTransferFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAdmFileTransfer(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addAdmFileTransfer(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: AdmFileTransferVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除档案移交编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmFileTransfer(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admFileTransfer/export', {
    ...queryParams.value
  }, `admFileTransfer_${new Date().getTime()}.xlsx`)
}

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 打开选择框
const openUserSelector = () => {
  userSelectTitle.value = '选择接受人员';
  currentSelectedUserIds.value = String(form.value.recipientId);
  currentSelectedUserNames.value = form.value.recipientName;
  userSelectVisible.value = true;
  currentActualStage.value = null;
  currentSelectStageIndex.value = -100;
};

// 处理使用人或共同使用人选择确认
const handleUserSelectWithIds = (data: { users: any[]; userIds: string; userNames: string }) => {
  const u = data.users[0];
  form.value.recipientId = u.userId;
  form.value.recipientName = u.userName;
  handleUserSelectCancel();
};

// 取消选择
const handleUserSelectCancel = () => {
  currentActualStage.value = null;
  currentSelectStageIndex.value = -1;
  currentSelectedUserIds.value = '';
  currentSelectedUserNames.value = '';
  userSelectVisible.value = false;
};

onMounted(() => {
  getList();
  fetchDeptTree();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block; /* 确保是块级元素 */
}
</style>